// https://vitepress.dev/guide/custom-theme
import { h, computed } from 'vue'
import { useData, type Theme } from 'vitepress'
import DefaultTheme from 'vitepress/theme'
import './custom.css'
import './ebnf.css'
// import './ebnf2.css'
import { serverAnalyticsService } from './services/serverAnalytics'
import { getGlobalVersion } from './composables/useVersion'
import { enhanceAppWithTabs } from 'vitepress-plugin-tabs/client'

import NotFound from "./components/NotFound.vue";
import AlterUserBlock from "./components/AlterUserBlock.vue";
import VersionReminder from "./components/VersionReminder.vue";
import VersionSwitcher from "./components/VersionSwitcher.vue";
import SvgLoader from "./components/SvgLoader.vue";
import ViewCount from "./components/ViewCount.vue";

export default {
  extends: DefaultTheme,
  Layout: () => {
    const { site, page, frontmatter, theme } = useData();
    const version = computed(() => String(theme.value.version?.display || ''));
    // const siteTitleHtml = computed(() => {
    //   return `<span class=\"site-version\">${version.value}</span>`;
    // });

    const children = {
      // "nav-bar-content-after": () => h('div', { class: 'site-title', innerHTML: siteTitleHtml.value }),
      "doc-before": () => [
        frontmatter.value.title
          ? h("h1", { class: "vp-doc" }, frontmatter.value.title)
          : null,
        h(VersionReminder),
      ],
      "aside-outline-before": () => h(VersionReminder),
      "footer": () => [
        h("span", { innerHTML: theme.value.footer?.copyright })
      ]
    };

    if (page.value.isNotFound) {
      children["not-found"] = () => h(NotFound);
    }

    return h(DefaultTheme.Layout, null, children);
  },
  setup() {
    // 在客户端环境下监听路由变化
    if (typeof window !== 'undefined') {
      let lastPath = ''
      let debounceTimer: NodeJS.Timeout | null = null
      
      // 防抖函数
      const debounce = (func: Function, delay: number) => {
        return (...args: any[]) => {
          if (debounceTimer) clearTimeout(debounceTimer)
          debounceTimer = setTimeout(() => func.apply(null, args), delay)
        }
      }
      
      // 监听路由变化
      const handleRouteChange = debounce(() => {
        const currentPath = window.location.pathname
        
        // 避免重复记录相同路径
        if (currentPath !== lastPath) {
          lastPath = currentPath
          // 记录页面访问，传递当前版本号
          const currentVersion = getGlobalVersion()
          serverAnalyticsService.trackPageView(undefined, currentVersion)
        }
      }, 300) // 300ms 防抖

      // 监听 popstate 事件（浏览器前进后退）
      window.addEventListener('popstate', handleRouteChange)
      
      // 监听 pushstate 和 replacestate 事件
      const originalPushState = history.pushState
      const originalReplaceState = history.replaceState
      
      history.pushState = function(...args) {
        originalPushState.apply(history, args)
        handleRouteChange()
      }
      
      history.replaceState = function(...args) {
        originalReplaceState.apply(history, args)
        handleRouteChange()
      }

      // 初始页面访问记录
      setTimeout(() => {
        lastPath = window.location.pathname
        const currentVersion = getGlobalVersion()
        serverAnalyticsService.trackPageView(undefined, currentVersion)
      }, 100)
    }
  },
  enhanceApp({ app, router, siteData }) {
    //因为只有一个版本，故暂时注释切换版本功能
    // app.component('VersionSwitcher', VersionSwitcher);
    app.component('SvgLoader', SvgLoader);
    app.component('ViewCount', ViewCount);
    app.component('AlterUserBlock', AlterUserBlock); // 注册 AlterUserBlock 组件
    enhanceAppWithTabs(app);
  }
} satisfies Theme
